import React, { createRef, useState } from 'react';
import { Card, Button, Modal } from 'antd';

import './index.css';
import TipTitle from '@/components/TipTitle';
import { createDsToJS, validateTableData } from '@/utils/utils';
import { isEmpty } from '@/utils/lodash';
import { fieldConfigRules } from './validateRules';

import BasicConfig from './BasicConfig';
import FieldConfig from './FieldConfig';
import FileInfoModal from './FileInfoModal';

const CreateDs: React.FunctionComponent<{}> = () => {
  
  const basicFormRef: any = createRef();
  const tableRef: any = createRef();
  const [modalVisible, setModalVisible] = useState(false);
  const [dsToJSData, setDsToJSData] = useState({});

  const createDsConfigFiles = async () => {
    const basicConfigData = await basicFormRef?.current?.getFormValues() || {};
    const fieldConfigData = tableRef?.current?.getFieldConfigData() || [];
    const { validate, errLine = '', errMessage = '' } = validateTableData('字段配置表格', fieldConfigData, fieldConfigRules) || {};
    if(isEmpty(basicConfigData)) {
      Modal.error({
        title: '请检查 "基础属性配置" | "拓展基础属性配置" 输入是否有错误!',
      });
    }else if(!validate && errLine && errMessage) {
      Modal.error({
        title: errLine,
        content: errMessage,
      });
    }else {
      const dsToJSData = createDsToJS(basicConfigData, fieldConfigData) || {};
      console.log(dsToJSData);
      setDsToJSData(dsToJSData);
      setModalVisible(true);
    }
  };

  // 关闭弹窗
  const handleModalCancel = () => {
    setModalVisible(false);
  }

  return (
    <>
      <Card
        title={<TipTitle title='基础属性配置'
        tip='根据默认配置生成DS的基础属性' />}
        className='basic-ds-config-card'
      >
        <BasicConfig ref={basicFormRef} />
        <Card
          title={<TipTitle title='字段配置'
          tip='根据默认配置生成DS的field和queryField属性' />}
          className='table-ds-config-card'
        >
          <FieldConfig ref={tableRef} />
        </Card>
      </Card>
      <div className='create-ds-button'>
        <Button type='primary' htmlType='submit' onClick={() => createDsConfigFiles()}>
          生成DS及配置文件
        </Button>
      </div>
      <FileInfoModal
        modalVisible={modalVisible}
        handleModalCancel={handleModalCancel}
        dsToJSData={dsToJSData}
      />
    </>
  );
}
 
export default CreateDs;
